<?php
	defined( "AZ_EXE_" ) or die ( "ERROR : CORE VARIABLE IS NOT DEFINED." );
	class MySQL extends AZ {
		private $host = null ;
		private $user = null ;
		private $password = null ;
		private $database = null ;
		public static $instance = null ;
		private $link = null ;
		
		private function openConnection(){
			$this->link = mysql_connect( MySQLConfig::HOST , MySQLConfig::USER , MySQLConfig::PASS , true );
			mysql_select_db( MySQLConfig::DBNAME , $this->link ) ;
			return $this->link;
		}
		public function executeQuery( $query ){
			date_default_timezone_set("Asia/Bangkok");
			$mysqlResults = null ;
			$this->openConnection();
			mysql_query("SET NAME=UTF-8");
			$mysqlResults = mysql_query($query,$this->link) or die ( "QUERY ERROR: " . $query . "<br/>" . mysql_error() ) ;
			$id = mysql_insert_id();
			$this->closeConnection();
			return $id!==0&&$id>0?$id:$mysqlResults ;
		}
		function esc_str($str = ""){//return $str;
			$link = $this->openConnection();			
			if($link){
				return mysql_real_escape_string($str);
			}else{
				return mysql_escape_string($str);
			}
		}
		public function sqlRealEscape($string){
			return $this->esc_str($string);
		}
		public function executeQueryAsObject( $query ){
			$mysqlResults = $this->executeQuery($query);
			return $this->resultToObject($mysqlResults);
		}
		public function executeQueryAsArray( $query ){
			date_default_timezone_set("Asia/Bangkok");
			$mysqlResults = $this->executeQuery($query);
			return $this->resultToArray($mysqlResults);
		}
		public function getRowWithQuery($query){
			$result = 0 ;
			if ( $query != false || $query != "" ){
				$this->openConnection();
				$result = mysql_query($query,$this->link) or die( "ERROR : " . $query );
				$result = mysql_num_rows($result);
			}
			return $result;
		}
		public function totalRows($tableName){
			$totalrows = 0 ;
			if ( $tableName != false || $tableName != ""){
				$totalrows = mysql_num_rows($this->executeQuery("SELECT * FROM $tableName ;"));
			}
			return $totalrows;
		}
		private function resultToObject( $mysqlResults ){
			$result = array();
			while( ( $mysqlResult = mysql_fetch_object($mysqlResults ) ) ){
				$result[] = $mysqlResult ;
			}
			return (count( $result ) > 0 ) ? $result : null ;
		}
		private function resultToArray( $mysqlResults ){
			$result = array();
			while( ( $mysqlResult = mysql_fetch_assoc($mysqlResults ) ) ){
				$result[] = $mysqlResult ;
			}
			return (count( $result ) > 0 ) ? $result : null ;
		}
		private function closeConnection(){
			mysql_close( $this->link );
		}
		
	}
?>